﻿using System;

public class NmeaUtility
{
    public static int ConvertToInt(string word)
    {
        try
        {
            char[] trimChars = new char[1];
            trimChars[0] = '0';
            return int.Parse(word.Trim(trimChars));
        }
        catch (Exception)
        {
            return default(int);
        }
    }

    public static double ConvertToDouble(string word)
    {
        try
        {
            return double.Parse(word,System.Globalization.NumberStyles.Any);
        }
        catch (Exception)
        {
            return default(double);
        }
    }

    public static DateTime ConvertSateliteTime(string word)
    {
        if (string.IsNullOrEmpty(word))
            throw new ArgumentNullException("word");

        // get main time

        int UtcHours;
        UtcHours = Convert.ToInt32(word.Substring(0, 2));

        int UtcMinutes;
        UtcMinutes = Convert.ToInt32(word.Substring(2, 2));

        int UtcSeconds;
        UtcSeconds = Convert.ToInt32(word.Substring(4, 2));

        // Extract milliseconds if it is available

        int UtcMilliseconds;
        UtcMilliseconds = 0;

        if (word.Length > 7)
            UtcMilliseconds = Convert.ToInt32(word.Substring(7));

        // Now build a DateTime object with all values

        System.DateTime Today;
        Today = System.DateTime.Now.ToUniversalTime();

        System.DateTime SatelliteTime;
        SatelliteTime = new System.DateTime(
            Today.Year, Today.Month, Today.Day, UtcHours, UtcMinutes, UtcSeconds, UtcMilliseconds);

        return SatelliteTime;
    }

    public static bool IsValidSentence(string sentence)
    {
        Int32 lastIndexOfStartSentence = sentence.LastIndexOf("$GPGGA");
        Int32 lastIndexOfEndSentence = sentence.LastIndexOf("*");
        return (lastIndexOfStartSentence > -1) && (lastIndexOfEndSentence > -1 && lastIndexOfEndSentence > lastIndexOfStartSentence);
    }

    public static string  LastSentence(string sentence)
    {
        Int32 lastIndexOfStartSentence = sentence.LastIndexOf("$GPGGA");
        Int32 lastIndexOfEndSentence = sentence.LastIndexOf("*");
        return sentence.Substring(lastIndexOfStartSentence, lastIndexOfEndSentence - lastIndexOfStartSentence + 3);
    }
}
